<?php
namespace zake\server\http;

use zake\helper\Console;

/**
 * Class Header
 * @package zake\server\http
 */
class Header
{


    private $_buffer = "";

    private $_connect = null;


    private $_bodyLength = 0;

    private $_headLength = 0;


    /**
     *
     * @param $headBuffer
     * @param HttpConnect $connect
     * @return null|false|static|Header
     *
     * @author liu.bin 2020-04-28 22:09
     */
    public static function parse($headBuffer,HttpConnect $connect)
    {
        $self = new static($headBuffer,$connect);
        return $self->build();
    }


    /**
     * Head constructor.
     * @param $headBuffer
     */
    protected function __construct($headBuffer,HttpConnect $connect)
    {
        $this->_buffer = $headBuffer;
        $this->_connect = $connect;
    }


    /**
     * 创建header对象
     *
     * @return bool|null|static
     *      null    继续等待
     *      false   关闭链接
     *      Header  创建成功
     *
     * @author liu.bin 2020-04-28 22:02
     */
    private function build()
    {
        $buffer = $this->_buffer;
        if (!strpos($buffer, "\r\n\r\n")) {
            if ($this->_connect->getRPos() > $this->_connect->headMaxLength) {
                return false;
            }
            return null;
        }
        list($headerBuffer,) = explode("\r\n\r\n", $buffer, 2);
        $this->_headLength = strlen($headerBuffer) + 4;
        $this->_bodyLength = $this->getContentLength($headerBuffer);
        return $this;
    }


    /**
     *
     * @param $header
     * @param $method
     * @return int|mixed
     *
     * @author liu.bin 2020-04-28 22:05
     */
    protected function getContentLength($headerBuffer)
    {
        $method = substr($headerBuffer, 0, strpos($headerBuffer, ' '));
        if($method === 'GET' || $method === 'OPTIONS' || $method === 'HEAD') {
            return 0;
        }
        $match = [];
        if (preg_match("/\r\nContent-Length: ?(\d+)/i", $headerBuffer, $match)) {
            $contentLength = isset($match[1]) ? $match[1] : 0;
            return $contentLength;
        }
        return 0;
    }



    public function getHeadLength()
    {
        return $this->_headLength;
    }


    public function getBodyLength()
    {
        return $this->_bodyLength;
    }




    private function _parsePathInfo($buffer)
    {
        if(strpos($buffer,"\r\n")){

            list($line,) = explode("\r\n",$buffer,2);
            return explode(" ",$line);
        }
        return ["no header","no header","no header"];
    }

    public function __destruct()
    {
        list($method,$path,$httpv) = $this->_parsePathInfo($this->_buffer);
        $fd = $this->_connect->getFd();
        //Console::success("http header __destruct. fd[{$fd}]. method[{$method}]. path[{$path}]. httpv[{$httpv}]");
    }
}
